<template>
  <div style="padding: 20px;height: 670px">
    <t-card style="height: 670px">
      <t-card shadow="never" style="width: 1320px">
        <el-form :inline="true" label-width="80px">
          <el-form-item label="支付时间">
            <el-date-picker
                v-model="searchParams.payTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="支付类型">
            <el-select v-model="searchParams.payType" placeholder="请选择支付类型">
              <el-option label="物业费" value="1"></el-option>
              <el-option label="水电费" value="2"></el-option>
              <el-option label="停车费" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="支付状态">
            <el-select v-model="searchParams.payStatus" placeholder="请选择支付状态">
              <el-option label="未支付" value="1"></el-option>
              <el-option label="已支付" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <t-button theme="primary" variant="outline" @click="search">搜索</t-button>
            &ensp;
            <t-button theme="primary" @click="reset">重置</t-button>
          </el-form-item>
        </el-form>
      </t-card>
      <!-- 表格展示数据 -->
      <br/>
      <t-card shadow="never" style="width: 1320px">
        <el-table :data="payList" style="height:450px">
          <el-table-column prop="payNum" label="支付编号"></el-table-column>
          <el-table-column prop="payTime" label="支付时间">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.payTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="payMoney" label="支付金额">
            <template slot-scope="scope">
              <span>{{ scope.row.payMoney + "元" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="payType" label="支付类型">
            <template slot-scope="scope">
              <span>{{ getPayTypeLabel(scope.row.payType) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="payStatus" label="支付状态">
            <template slot-scope="scope">
              <span>{{ getPayStatusLabel(scope.row.payStatus) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="payWay" label="支付方式">
            <template slot-scope="scope">
              <span>{{ getPayWayLabel(scope.row.payWay) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="payMark" label="备注">
            <template slot-scope="scope">
              <span>{{ scope.row.payMark }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <t-button @click="editPay(scope.row)" theme="primary" size="small">编辑</t-button>
              <el-popconfirm
                  title="确定要删除吗？"
                  confirmButtonText="确定"
                  cancelButtonText="取消"
                  @confirm="deletePay(scope.row)"
                  @cancel="cancelDelete"
              >
                <t-button theme="primary" variant="outline" size="small" slot="reference">删除</t-button>
              </el-popconfirm>
              <!-- 添加支付按钮 -->
              <t-button v-if="scope.row.payStatus==='1'" @click="goToPayment(scope.row)" theme="primary"
                        variant="dashed" size="small">去支付
              </t-button>
            </template>
          </el-table-column>
        </el-table>
        <btr/>
        <el-pagination
            @size-change="handlePageSizeChange"
            @current-change="handleCurrentPageChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>

        <el-dialog :visible="dialogVisible" :title="dialogTitle" @close="closeDialog">
          <el-form :model="currentPay" label-width="80px">
            <el-form-item label="支付编号">
              <el-input v-model="currentPay.payNum" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="支付时间">
              <el-date-picker v-model="currentPay.payTime" type="datetime"></el-date-picker>
            </el-form-item>
            <el-form-item label="支付金额">
              <el-input v-model="currentPay.payMoney" type="number"></el-input>
            </el-form-item>
            <el-form-item label="支付类型">
              <el-select v-model="currentPay.payType">
                <el-option label="物业费" value="1"></el-option>
                <el-option label="水电费" value="2"></el-option>
                <el-option label="停车费" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="支付状态">
              <el-select v-model="currentPay.payStatus">
                <el-option label="未支付" value="1"></el-option>
                <el-option label="已支付" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="支付方式">
              <el-select v-model="currentPay.payWay">
                <el-option label="现金支付" value="1"></el-option>
                <el-option label="支付宝支付" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="currentPay.payMark"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="savePay">保存</el-button>
            <el-button @click="closeDialog">取消</el-button>
          </div>
        </el-dialog>

        <!-- 添加支付记录的按钮 -->
        <div ref="alipayWap" v-html="alipay"/>
      </t-card>
    </t-card>
  </div>
</template>

<script>
import axios from 'axios';
import {MessagePlugin} from "tdesign-vue";

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "pays",
  data() {
    return {
      alipayWap: "",
      alipay: "",
      payList: [], // 支付记录列表
      dialogVisible: false, // 对话框是否可见
      dialogTitle: '', // 对话框标题
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示的条数
      total: 0,
      currentPay: { // 当前编辑/添加的支付记录
        payId: null,
        payNum: '',
        payTime: '',
        payMoney: null,
        payType: '',
        payStatus: '',
        payWay: '',
        payMark: ''
      },
      searchParams: {
        payTime: "",
        payStatus: "",
        payType: ""
      }
    };
  },
  mounted() {
    this.fetchPayList();
  },
  methods: {
    formatDateTime(dateTime) {
      if (!dateTime) {
        return '';
      }
      const formattedDateTime = new Date(dateTime).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
      });
      return formattedDateTime;
    },
    goToPayment(pay) {
      const that = this;

      // 将订单信息发送给后端接口进行支付
      axios.post('/api/admin/pay/topay', pay)
          .then(response => {

            // 处理支付成功的逻辑，例如跳转到支付成功页面
            this.alipay = response.data.data;
            // 防抖避免重复支付
            this.$nextTick(() => {
              // 提交支付表单
              this.$refs.alipayWap.children[0].submit();
              setTimeout(() => {
                // this.toPayFlag = false;
              }, 500);
            });
            that.fetchPayList();

          })
          .catch(error => {
            // 处理支付失败的逻辑，例如显示错误提示信息
            console.error(error);
            // this.$message.error('支付失败，请重试！');
          });
    },
    // 获取支付记录列表
    fetchPayList() {
      const pageNum = this.currentPage;
      const pageSize = this.pageSize;
      const pay = this.searchParams;
      axios.post(`/api/admin/pay/getPageByCondition?pageNum=${pageNum}&pageSize=${pageSize}`, pay)
          .then(response => {
            this.payList = response.data.data.list;
            this.total = Number(response.data.data.total);
          })
          .catch(error => {
            console.error(error);
          });
    },
    // 添加支付记录
    addPay() {
      this.dialogTitle = '添加支付记录';
      this.currentPay = {
        payId: null,
        payNum: '',
        payTime: '',
        payMoney: null,
        payType: '',
        payStatus: '',
        payWay: '',
        payMark: ''
      };
      this.dialogVisible = true;
    },
    // 编辑支付记录
    editPay(pay) {
      this.dialogTitle = '编辑支付记录';
      this.currentPay = Object.assign({}, pay);
      this.dialogVisible = true;
    },
    // 保存支付记录
    savePay() {
      axios.post('/api/admin/pay/updatePay', this.currentPay)
          .then(response => {
            console.log(response)
            this.closeDialog();
            this.fetchPayList();
            MessagePlugin.success('支付记录保存成功');
          })
          .catch(error => {
            console.error(error);
            MessagePlugin.error('保存失败，请重试！');
          });
    },
    // 删除支付记录
    deletePay(pay) {
      axios.post(`/api/admin/pay/delete?payId=${pay.payId}`)
          .then(response => {
            this.fetchPayList();
            if (response.data.code == 200) {

              MessagePlugin.success('删除成功');
            } else {
              MessagePlugin.error('删除失败，请重试！');
            }
          })
          .catch(error => {
            console.error(error);
          });
    },
    // 筛选支付记录
    search() {
      const pay = this.searchParams;
      const pageNum = this.currentPage;
      const pageSize = this.pageSize;

      axios.post(`/api/admin/pay/getPageByCondition?pageNum=${pageNum}&pageSize=${pageSize}`, pay, {
        headers: {
          "Content-Type": "application/json"
        },
      })
          .then(res => {
            if (res.data.code == 200) {
              this.payList = res.data.data.list;
              this.total = Number(res.data.data.total);
            } else {
              MessagePlugin.error('暂无数据')
            }
          });
    },
    // 重置搜索条件
    reset() {
      this.searchParams = {
        payTime: "",
        payType: "",
        payStatus: ""
      };
    },
    // 分页相关方法
    handlePageSizeChange(pageSize) {
      this.pageSize = pageSize;
    },
    handleCurrentPageChange(currentPage) {
      this.currentPage = currentPage;
    },
    // 关闭对话框
    closeDialog() {
      this.dialogVisible = false;
    },
    // 获取支付类型的标签
    getPayTypeLabel(payType) {
      switch (payType) {
        case '1':
          return '物业费';
        case '2':
          return '水电费';
        case '3':
          return '停车费';
        default:
          return '';
      }
    },
    // 获取支付状态的标签
    getPayStatusLabel(payStatus) {
      switch (payStatus) {
        case '1':
          return '未支付';
        case '2':
          return '已支付';
        default:
          return '';
      }
    },
    // 获取支付方式的标签
    getPayWayLabel(payWay) {
      switch (payWay) {
        case '1':
          return '现金支付';
        case '2':
          return '支付宝支付';
        default:
          return '';
      }
    },
  }
};
</script>

<style>
.pays-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pay-table {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
}

.pay-dialog {
  width: 60%;
  max-width: 500px;
}

.add-pay-button {
  margin-top: 20px;
}
</style>
